package com.leap.mini;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.leap.entity.Account;
import com.leap.properties.WeChatProperties;
import com.leap.service.AccountService;
import com.leap.utils.BeanUtils;
import com.leap.utils.HttpClientUtil;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MiniAuthenticationProvider implements AuthenticationProvider {
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String code = (String) authentication.getPrincipal();
        WeChatProperties weChatProperties = BeanUtils.getBean(WeChatProperties.class);
        AccountService accountService = BeanUtils.getBean(AccountService.class);
        Map<String,String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppId());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");

        String json = HttpClientUtil.doGet(WeChatProperties.WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        Account account = accountService.loadUserById(openid);
        MiniAuthenticationToken result = MiniAuthenticationToken.authenticated(openid, null,null);
        result.setDetails(account);
        return result;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return MiniAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
